<?php

namespace backend\controllers;

use Yii;
use backend\models\Navigation;
use backend\models\NavigationSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\controllers\CategoryController;

/**
 * NavigationController implements the CRUD actions for Navigation model.
 */
class NavigationController extends Controller {

    private $model;

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function init() {
        parent::init();
        $this->model = new Navigation();
    }

    /**
     * Lists all Navigation models.
     * @return mixed
     */
    public function actionIndex() {
       
    //   Yii::$app->db->getSchema()->refresh();
        
        
        $searchModel = new NavigationSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $data = $this->GetNavigationTree();

        
        if (count($data) > 0) {
            $models = $dataProvider->getModels();

            $sortList = array();
            foreach ($models as $k => $v) {

                foreach ($data as $key => $value) {

                    if (preg_replace("/[└|╍]*?/u", "", $value['name']) == $v->name) {
                        $v->name = $value['name'];
                        $sortList[$k] = $key;
                    }
                }
            }

            $modelsSorted = array();
            //更新 Key
            foreach ($sortList as $k => $v) {

                $modelsSorted[$v] = $models[$k];
            }

            ksort($modelsSorted);
     
            
            $dataProvider->setModels($modelsSorted);
        }




        return $this->render('index', [
                    'searchModel' => $searchModel,
                    'dataProvider' => $dataProvider,
                     'model' => $this->model,
                     'data' => $this->GetNavigationTree(),
        ]);
    }

    /**
     * Displays a single Navigation model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id) {
        return $this->render('view', [
                    'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Navigation model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $this->layout = false;

        if (!Yii::$app->request->isPost) {

            //渲染模板
            return $this->render('create', [
                        'model' => $this->model,
                        'data' => $this->GetNavigationTree(),
            ]);
        } else {
            
            if ($this->model->load(Yii::$app->request->post()) && $this->model->save()) {

                Yii::$app->session->setFlash("success", "类目创建成功");

                return $this->redirect(\yii\helpers\Url::toRoute("/navigation/index"));
            } else {

                Yii::$app->session->setFlash("error", "添加失败,请检测标题和标识 不能重复，而且不能为空");

                return $this->redirect(\yii\helpers\Url::toRoute("/navigation/index"));
            }
        }
    }

    public static function GetNavigationTree() {


        $data = array();
        $condition = array(
                // 'status'=>1,
        );
        $data = Navigation::find()->andWhere($condition)->asArray()->all();



        $data = \backend\controllers\CategoryController::CategoryTree($data, "parent");

        $data = \backend\controllers\CategoryController::CategoryTree2parr($data, "name");

        return $data;
    }

    /**
     * Updates an existing Navigation model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id) {
        
        
             $this->layout = false;
              $model = $this->findModel($id);

        
        if(Yii::$app->request->isPost){
            
            if($model->load(Yii::$app->request->post()) && $model->save()){
                
                Yii::$app->session->setFlash("success","更新成功");
            }else{
                Yii::$app->session->setFlash("error","更新失败");
            }
            
            return $this->redirect(\yii\helpers\Url::toRoute("/navigation/index"));
            
        }else{
            return $this->render('update', [
                    'model' => $model,
                    'data' => $this->GetNavigationTree(),
                    'nameAttribute' => $model->name,
                ]);
            
        }
   
    }

    /**
     * Deletes an existing Navigation model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id) {
        $this->findModel($id)->delete();
        
        Yii::$app->session->setFlash("success", "删除导航成功");
        
        return $this->redirect(['index']);
    }

    /**
     * Finds the Navigation model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Navigation the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if (($model = Navigation::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}
